//
// brief: 	设备服务器
// author： 	yun
// date: 	2017-01-21
//
// desc:	终端设备连接点
// version: v0.9
//
//

package worker

import (
	"net"
	"homeserver/logs"
	"io/ioutil"
	"encoding/json"
)


// 设备服务配置地址
type SevDeviceConf struct {
	Address 	string		`json:"sev_device_address"`
}


// 配置文件
var (
	sever_conf_file = "conf/services.json"
	devices_log_file = "running/dev_logger.txt"
	devices_event_file = "running/dev_event.txt"

	devLogger *logs.Logger
	evtLogger *logs.Logger
)

// 日志文件初始化
func init() {
	devLogger = logs.NewLogger(devices_log_file)
	evtLogger = logs.NewLogger(devices_event_file)
}

//
//  设备连接服务器开启
//
func StartService(end chan bool) {
	evtLogger.Notice("device service: establish")

	// 获取设备服务IP地址
	buf, err := ioutil.ReadFile(sever_conf_file)
	if err != nil {
		logs.Err("services.conf not found!")
		end <- true
		return
	}

	var sev_conf SevDeviceConf
	err = json.Unmarshal(buf, &sev_conf)
	if err != nil || sev_conf.Address == "" {
		evtLogger.Error("sevice device conf err!")
		end <- true
		return
	}


	l, err := net.Listen("tcp", sev_conf.Address)
	if err != nil {
		evtLogger.Error("device service err: ", err)
		end <- true
	}

	for {
		conn, err := l.Accept()
		if err != nil {
			evtLogger.Error("device service accept err: ", err)
			end <- true
		}

		go HandleConn(conn)
	}

}
